#include "stdafx.h"
#include "log.h"
#include "util\util.h"

#pragma warning(disable : 4996)
using namespace std;

namespace shared
{
    Log::Log()
    {
        ::InitializeCriticalSection(&m_lock);
        SetLogFile("c:\\info.log");
    }

    Log::~Log()
    {
        ::DeleteCriticalSection(&m_lock);
    }

    void Log::SetLogFile(char *file)
    {
        assert(m_file.empty());
        m_file = file;
    }

    bool Log::Write(const char *info)
    {
        if (m_file.empty())
            return false;
        bool ret = true;
        std::string time = QWinSys::GetSysTime("[", "] ");

        ::EnterCriticalSection(&m_lock);
        FILE *f = fopen(m_file.c_str(), "a+");
        if (!f){
            ret = false;
            goto end;
        }
        if (1 != fwrite(time.c_str(), time.length(), 1, f)){
            ret = false;
            goto end;
        }
        if (1 != fwrite(info, strlen(info), 1, f)){
            ret = false;
            goto end;
        }
        fwrite("\n", 1, 1, f);
    end:
        if (f)
            fclose(f);
        ::LeaveCriticalSection(&m_lock);
        return ret;
    }
}